﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using DDay.iCal;
using DDay.iCal.Components;
using DDay.iCal.DataTypes;
using DDay.iCal.Serialization;
using SelArom.Net.Sitefinity.API.Events;
using SelArom.Net.Sitefinity.API.Events.Data;
using Telerik.Events;
using System.Collections;
using System.Configuration;
using Telerik.Cms.Engine;

namespace SelArom.Net.Sitefinity.HttpHandlers
{
	/// <summary>
	/// HttpHandler for constructing an iCal feed from default provider
	/// </summary>
	public class CalendarFeed : IHttpHandler
	{
		protected IList events;

		public void ProcessRequest(HttpContext context)
		{
			var host = context.Request.Url.Host;

			// TODO: Support Filtering by date/month

			// TODO: Support filtering by category

			// initializie calendar
			var cal = new iCalendar();
			cal.Version = "1.0";

			// get events +/- 6 months
			var mgr = new EventsManager(EventsManager.DefaultContentProvider);
			events = mgr.GetEvents(DateTime.Now.AddMonths(-6), DateTime.Now.AddMonths(6), "Start ASC");
			foreach (IEvent ev in events)
			{
				var appt = new Event(cal);
				appt.Start = ev.Start.ToUniversalTime();
				appt.End = ev.End.ToUniversalTime();

				// save and format description
				var description = ev.ContentItem.Content.ToString().Replace("\r\n", "<br /><br/>");
				description = description.Replace("src=\"/", "src=\"http://" + host + "/");
				appt.AddProperty("X-ALT-DESC", description);

				// non-html property
				var reg = new Regex("<(.|\n)+?>");
				appt.Description = reg.Replace(description, "");

				// event location
				var location = ev.ContentItem.GetMetaData("Location");
				location = location == null ? ev.ContentItem.GetMetaData("Street") : string.Concat(location, " (", ev.ContentItem.GetMetaData("Street"), ")");
				appt.Location = location.ToString();

				appt.Summary = ev.EventTitle;

				// url
				var evUrl = ConfigurationManager.AppSettings[EventsManager.DefaultContentProvider + "Url"];
				if (string.IsNullOrEmpty(evUrl)) break;
				appt.Url = string.Concat("http://", host, evUrl, ev.ContentItem.UrlWithExtension);
				cal.Events.Add(appt);
			}

			// write calendar feed!
			var ser = new iCalendarSerializer(cal);
			context.Response.Clear();
			context.Response.ContentType = "text/calendar";
			context.Response.AddHeader("content-disposition", "attachment; filename=Calendar.ics");
			context.Response.Write(ser.SerializeToString());
			//context.Response.Flush();
		}

		public bool IsReusable
		{
			get { return false; }
		}
	}
}
